//
//  VersionUtil.m
//  xychain_DM_iOS
//
//  Created by Jpwang on 2018/6/8.
//  Copyright © 2018年 Jpwang. All rights reserved.
//

#import "VersionUtil.h"

@interface VersionUtil() {
    void (^mBlock)(NSString *version, NSError *error);
    void (^mBlock2)(BOOL isNeedUpdate, NSError *error);
}

@end

@implementation VersionUtil

+ (VersionUtil *)shareInstance {
    static VersionUtil *_sharedInstance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[VersionUtil alloc] init];
    });
    return _sharedInstance;
}

- (void)checkVersion:(NSString *)urlstr block:(void (^)(NSString *onlineVersion, NSError *error))block {
    mBlock = [block copy];
    NSURL *url          = [NSURL URLWithString:urlstr];
    NSURLRequest *req   = [NSURLRequest requestWithURL:url];
    [NSURLConnection connectionWithRequest:req delegate:self];
}

- (void)isNeedUpdate:(NSString *)urlstr block:(void (^)(BOOL isNeedUpdate, NSError *error))block {
    mBlock2 = [block copy];
    NSURL *url          = [NSURL URLWithString:urlstr];
    NSURLRequest *req   = [NSURLRequest requestWithURL:url];
    [NSURLConnection connectionWithRequest:req delegate:self];
}

- (BOOL)isNeedUpdate:(NSString *)onLineVersion {
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version       = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    BOOL result = [app_Version compare:onLineVersion] == NSOrderedAscending;
    return result;
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(nonnull NSData *)data {
    NSError *error;
    id jsonObject           = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
    NSDictionary *appInfo   = (NSDictionary*)jsonObject;
    NSArray *infoContent    = [appInfo objectForKey:@"results"];
    if (infoContent && infoContent.count>0) {
        NSString * version      = [[infoContent objectAtIndex:0]objectForKey:@"version"];//线上最新版本
        if (mBlock) {
            mBlock(version, nil);
        }
        if (mBlock2) {
            mBlock2([self isNeedUpdate:version], nil);
        }
    } else {
        if (mBlock) {
            mBlock(nil, error);
        }
        if (mBlock2) {
            mBlock2(NO, error);
        }
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    if (mBlock) {
        mBlock(nil, error);
    }
    if (mBlock2) {
        mBlock2(NO, error);
    }
}


@end
